import mqtt from 'mqtt';
import { ref } from 'vue';

// MQTT连接配置
const mqttConfig = {
  host: 'kf9d2a91.ala.cn-hangzhou.emqxsl.cn',  // 使用公共测试服务器
  port: 8084, // WebSocket SSL端口
  protocol: 'wss',
  username: 'reisen7', // 如果需要认证，请修改为实际的用户名
  password: 'if5:a:R4sXXdE2A', // 如果需要认证，请修改为实际的密码
  clientId: 'vue_chess_' + Date.now() + '_' + Math.random().toString(16).substring(2, 8),
  clean: true,
  connectTimeout: 8000, // 增加连接超时时间
  reconnectPeriod: 2000, // 增加重连间隔
  keepalive: 60, // 保持连接活跃
};

// MQTT主题 - 使用固定主题以确保所有用户都在同一频道
const topics = {
  GAME_MATCHING: 'chess/matching_channel',
  GAME_PLAY: 'chess/play_channel',
  GAME_ROOM: 'chess/room_channel/',
};

console.log('使用象棋MQTT主题:', topics);

class MQTTService {
  constructor() {
    this.client = null;
    this.connected = ref(false);
    this.connectionStatus = ref('未连接');
    this.messages = ref([]);
    this.subscriptions = new Set();
  }

  // 连接到MQTT服务器
  connect() {
    return new Promise((resolve, reject) => {
      const { host, port, protocol } = mqttConfig;
      const url = `${protocol}://${host}:${port}/mqtt`;
      
      this.connectionStatus.value = '正在连接...';
      console.log(`正在连接MQTT服务器: ${url}`);
      
      if (this.client) {
        console.log('已存在MQTT客户端，先断开连接');
        this.client.end(true);
        this.client = null;
      }
      
      this.client = mqtt.connect(url, mqttConfig);

      // 设置连接超时
      const connectionTimeout = setTimeout(() => {
        if (!this.connected.value) {
          this.connectionStatus.value = '连接超时';
          console.error('MQTT连接超时');
          reject(new Error('MQTT连接超时'));
        }
      }, 10000);

      this.client.on('connect', () => {
        clearTimeout(connectionTimeout);
        console.log('已成功连接到MQTT服务器');
        this.connected.value = true;
        this.connectionStatus.value = '已连接';
        
        // 连接成功后，立即订阅所有主题
        this.subscribeToAllTopics();
        resolve();
      });

      this.client.on('error', (error) => {
        console.error('MQTT连接错误:', error);
        this.connected.value = false;
        this.connectionStatus.value = `连接错误: ${error.message}`;
        reject(error);
      });

      this.client.on('message', (topic, message) => {
        try {
          console.log(`收到原始消息 [${topic}]: ${message.toString()}`);
          const parsedMessage = JSON.parse(message.toString());
          this.messages.value.push({ topic, message: parsedMessage, timestamp: new Date() });
          console.log(`解析后的消息:`, parsedMessage);
        } catch (error) {
          console.error('解析消息失败:', error, message.toString());
        }
      });

      this.client.on('reconnect', () => {
        console.log('正在重新连接到MQTT服务器...');
        this.connectionStatus.value = '重新连接中...';
      });

      this.client.on('disconnect', () => {
        console.log('已断开与MQTT服务器的连接');
        this.connected.value = false;
        this.connectionStatus.value = '已断开';
      });
      
      this.client.on('close', () => {
        console.log('MQTT连接已关闭');
        this.connected.value = false;
        this.connectionStatus.value = '已关闭';
      });
      
      this.client.on('offline', () => {
        console.log('MQTT客户端离线');
        this.connected.value = false;
        this.connectionStatus.value = '离线';
      });
    });
  }
  
  // 订阅所有主题
  subscribeToAllTopics() {
    console.log('正在订阅所有主题...');
    // 订阅匹配主题
    this.subscribe(topics.GAME_MATCHING);
    // 订阅游戏主题
    this.subscribe(topics.GAME_PLAY);
    console.log('所有主题订阅请求已发送');
  }

  // 订阅主题
  subscribe(topic) {
    console.log(`正在订阅主题: ${topic}`);
    
    if (!this.client) {
      console.error('MQTT客户端未初始化，无法订阅主题');
      return;
    }
    
    this.client.subscribe(topic, { qos: 1 }, (error, granted) => {
      if (error) {
        console.error(`订阅主题 ${topic} 失败:`, error);
      } else {
        console.log(`已成功订阅主题: ${topic}`, granted);
        this.subscriptions.add(topic);
      }
    });
  }

  // 取消订阅主题
  unsubscribe(topic) {
    if (this.client) {
      this.client.unsubscribe(topic, (error) => {
        if (error) {
          console.error(`取消订阅主题 ${topic} 失败:`, error);
        } else {
          console.log(`已取消订阅主题: ${topic}`);
          this.subscriptions.delete(topic);
        }
      });
    }
  }

  // 发布消息
  publish(topic, message) {
    console.log(`正在发布消息到主题: ${topic}`, message);
    
    if (!this.client) {
      console.error('MQTT客户端未初始化，无法发布消息');
      return false;
    }
    
    if (!this.connected.value) {
      console.error('MQTT客户端未连接，无法发布消息');
      return false;
    }
    
    const messageStr = JSON.stringify(message);
    return new Promise((resolve, reject) => {
      this.client.publish(topic, messageStr, { qos: 1 }, (error) => {
        if (error) {
          console.error(`发布消息到主题 ${topic} 失败:`, error);
          reject(error);
        } else {
          console.log(`已成功发布消息到主题: ${topic}`);
          resolve(true);
        }
      });
    });
  }

  // 断开连接
  disconnect() {
    if (this.client) {
      this.client.end();
      this.connected.value = false;
      this.connectionStatus.value = '已断开';
      this.subscriptions.clear();
      console.log('已断开与MQTT服务器的连接');
    }
  }
  
  // 取消所有订阅
  unsubscribeAll() {
    console.log('取消所有主题的订阅');
    if (this.client) {
      // 复制一份订阅集合，因为在循环中会修改原集合
      const subscriptionsCopy = [...this.subscriptions];
      subscriptionsCopy.forEach(topic => {
        this.unsubscribe(topic);
      });
      console.log('已取消所有主题的订阅');
    } else {
      console.warn('MQTT客户端未初始化，无法取消订阅');
    }
  }
}

// 导出单例
export const mqttService = new MQTTService();
export { topics }; 